package com.example.fang.demodruid.config.shiro.filters;

import com.example.fang.demodruid.common.ShiroConstants;
import com.example.fang.demodruid.config.shiro.ShiroUtils;
import com.example.fang.demodruid.entity.SysUser;
import com.example.fang.demodruid.util.StringUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.util.Deque;

/**
 * @describe: 退出过滤器
 * @author:01410843
 * @Date 2022/7/14 10:49
 **/
public class LogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter{

    private static final Logger log = LoggerFactory.getLogger(LogoutFilter.class);

    /**
     * 退出后重定向的地址
     */
    private String loginUrl;

    private Cache<String, Deque<Serializable>> cache;

    public String getLoginUrl() {
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception{
        try {
            Subject subject = getSubject(request, response);
            String redirectUrl = getRedirectUrl(request, response, subject);
            try {
                SysUser user = ShiroUtils.getSysUser();
                if (StringUtils.isNotNull(user)){
                    String loginName = user.getLoginName();
                    //TODO 记录用户退出日志

                    //TODO 清理缓存
                }
                // 退出登录
                subject.logout();
            }catch (Exception e){
                log.error("logout fail.", e);
            }
            issueRedirect(request, response, redirectUrl);
        }catch (Exception e){
            log.error("Encountered session exception during logout.  This can generally safely be ignored.", e);
        }
        return  false;
    }


    // 设置Cache的key的前缀
    public void setCacheManager(CacheManager cacheManager) {
        // 必须和ehcache缓存配置中的缓存name一致
        this.cache = cacheManager.getCache(ShiroConstants.SYS_USERCACHE);
    }
}
